﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using OpenExpressApp.Module.Library.Security;
using OpenExpressApp.MetaModel.Utils;
using OpenExpressApp.MetaModel.Audit;
using OpenExpressApp.Module.Library;
using Csla;
using OpenExpressApp.Host.WPF;

namespace OpenExpressApp
{
    /// <summary>
    /// Interaction logic for LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        private bool _result;

        public LoginWindow()
        {
            this._result = false;
            InitializeComponent();
            txtUserName.Text = AppConfig.Instance.LoginName;
        }

        public bool Result
        {
            get
            {
                return this._result;
            }
            set
            {
                this._result = value;
            }
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            this._result = false;
            if (OEAPrincipal.Login(txtUserName.Text, StringHelper.MD5(txtPassword.Password)) == false)
            {
                MessageBox.Show("用户或密码错误，请重新输入！", "登录失败");

                AuditLogService.LogAsync(new AuditLogItem()
                {
                    Title = "登录失败",
                    Type = AuditLogType.Login
                });
            }
            else
            {
                //记录登录用户名
                AppConfig.Instance.LoginName = txtUserName.Text;
                AppConfig.Instance.Save();
                User user = (ApplicationContext.User.Identity as OEAIdentity).User;

                this._result = user.TryLogin();
                if (this._result == false)
                {
                    MessageBox.Show("登录次数已到！");
                }

                AuditLogService.LogAsync(new AuditLogItem()
                {
                    Title = this._result ? "登录成功" : "登录次数已到",
                    Type = AuditLogType.Login
                });

                this.Close();
            }
        }

        private void Cancel(object sender, RoutedEventArgs e)
        {
            this._result = false;
            this.Close();
        }

        public static bool Execute()
        {
            Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;  //防止登录后Application退出
            LoginWindow loginWin = new LoginWindow();
            loginWin.ShowDialog();
            Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
            return loginWin.Result;
        }
    }
}